package cn.schoolwow.quickdao.module.database.parent.flow.executor.common;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.entity.SqlLog;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class InsertSqlLogFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        setSqlLog(flowContext);
        insertSqlLog(flowContext);
    }

    @Override
    public String name() {
        return "插入SQL日志";
    }

    private void setSqlLog(FlowContext flowContext){
        String sql = flowContext.checkData("sql", String.class);
        String formatSQL = flowContext.checkData("formatSQL", String.class);
        Exception e = flowContext.getData("exception", Exception.class);
        List parameters = flowContext.getData("parameters", List.class);
        String name = flowContext.checkData("name", String.class);
        long startTime = flowContext.checkData("startTime", long.class);
        int sqlLogType = flowContext.checkData("sqlLogType", int.class);
        Integer effect = flowContext.getData("effect", Integer.class);

        long endTime = System.currentTimeMillis();
        long consumeTime = endTime-startTime;

        SqlLog sqlLog = new SqlLog();
        sqlLog.setType(sqlLogType);
        sqlLog.setName(name);
        sqlLog.setConsumeTime(consumeTime);
        sqlLog.setStatement(sql);
        sqlLog.setFormatStatement(formatSQL);
        if(null!=parameters&&!parameters.isEmpty()){
            sqlLog.setParameters(parameters.toString());
        }
        sqlLog.setEffect(effect);
        if(null!=e){
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            sqlLog.setException(sw.toString());
        }
        flowContext.putData("sqlLog", sqlLog);
    }

    private void insertSqlLog(FlowContext flowContext) throws InterruptedException {
        Boolean insertSqlLog = (Boolean) flowContext.getData("insertSqlLog");
        if(null!=insertSqlLog&&!insertSqlLog){
            return;
        }

        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        SqlLog sqlLog = (SqlLog) flowContext.checkData("sqlLog");
        if(quickDAOConfig.logRecordOption.recordSqlLog){
            quickDAOConfig.logRecordOption.sqlLogBlockingQueue.offer(sqlLog, 3, TimeUnit.SECONDS);
        }
    }
}
